package com.wl.boot.batch.service.impl;

import com.wl.boot.batch.bean.entity.CommonExcelConfig;
import com.wl.boot.batch.bean.entity.CommonExcelPageField;
import com.wl.boot.batch.mapper.excelMapper;
import com.wl.boot.batch.service.ExcelAsyncService;
import com.wl.boot.batch.service.ExcelService;
import com.wl.boot.batch.util.EECUtil;
import com.wl.boot.batch.util.EasyExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author wanglu
 */
@Service
public class ExcelServiceImpl implements ExcelService {
    private Logger logger = LoggerFactory.getLogger(ExcelServiceImpl.class);
    @Autowired
    private excelMapper dao;

    @Autowired
    private ExcelAsyncService asyncService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void parserExcel(MultipartFile file, String excelId) throws Exception {
        StopWatch sw = new StopWatch();
        logger.info(">>>>>>>>>>>> 开始：");
        sw.start();
        CommonExcelConfig ec = dao.getExcelConfigByExcelId(excelId);
        List<CommonExcelPageField> epf = dao.getExcelPageFieldByExcelId(ec.getConfigId());
        EasyExcelUtil.readExcel(file, ec, epf, this);
        sw.stop();
        logger.info("<<<<<<<<<<<< 结束：" + sw.getLastTaskTimeMillis() / 1000 + "s");

    }

    @Override
    public void parserExcels(MultipartFile[] files, String excelId) throws Exception {
        StopWatch sw = new StopWatch();
        logger.info(">>>>>>>>>>>> 开始：");
        sw.start();
        CommonExcelConfig ec = dao.getExcelConfigByExcelId(excelId);
        List<CommonExcelPageField> epf = dao.getExcelPageFieldByExcelId(ec.getConfigId());
        List<MultipartFile> list = Arrays.asList(files);
        list.stream().forEach(f -> {
            try {
                EasyExcelUtil.readExcel(f, ec, epf, this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        sw.stop();
        logger.info("<<<<<<<<<<<< 结束：" + sw.getLastTaskTimeMillis() / 1000 + "s");
    }

    @Override
    public void parserExcelEEC(MultipartFile file, String excelId) throws IOException, InterruptedException {
        StopWatch sw = new StopWatch();
        logger.info(">>>>>>>>>>>> 开始：");
        sw.start();
        List<Object> list = EECUtil.streamRead(file.getInputStream());
        CommonExcelConfig ec = dao.getExcelConfigByExcelId(excelId);
        List<CommonExcelPageField> epf = dao.getExcelPageFieldByExcelId(ec.getConfigId());
        if (list.size() > 0) {

            //为了防止SQL语句超出长度出错，分成几次插入
            if (list.size() <= 3000) {
                dao.batchTargetTable(ec.getTargetTable(), list, epf);
            } else {
                int length = list.size();
                // 计算可以分成多少组
                int num = (length + 3000 - 1) / 3000;
                for (int i = 0; i < num; i++) {
                    // 开始位置
                    int fromIndex = i * 3000;
                    // 结束位置
                    int toIndex = (i + 1) * 3000 < length ? (i + 1) * 3000 : length;
                    dao.batchTargetTable(ec.getTargetTable(), list.subList(fromIndex, toIndex), epf);
                }
            }
        }
        sw.stop();
        logger.info("<<<<<<<<<<<< 结束：" + sw.getLastTaskTimeMillis() / 1000 + "s");
    }

    @Transactional(rollbackFor = Exception.class)
    public void MybatisForeachBatch(List datas, List<CommonExcelPageField> fields, String tableName) {
        dao.batchTargetTable(tableName, datas, fields);
    }
}
